import { Directive, ElementRef } from '@angular/core';
import { interval, Observable, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';

@Directive({
  selector: '[appScrollOrder]',
})
export class ScrollOrderDirective {
  itemContainerHeight!: number;
  itemSize!: number;
  interval$!: Subscription;
  currentItem: number = 0;
  constructor(private el: ElementRef) {}
  ngOnInit(): void {
    this.goBottom();
  }
  ngAfterViewChecked(): void {
    const arr: Array<any> = Array.from(
      this.el.nativeElement.getElementsByClassName('item-container')
    );
    this.itemContainerHeight = arr[0]?.scrollHeight;
    this.itemSize = arr.length;
  }
  goBottom() {
    this.interval$ = interval(2000)
      .pipe(
        map((elapse) => {
          this.currentItem = elapse % this.itemSize;
          return (elapse % this.itemSize) * this.itemContainerHeight;
        })
      )
      .subscribe((height) => {
        this.scrollTop(height);
      });
  }
  scrollTop(height: number) {
    if (this.itemSize === 2) {
      this.interval$.unsubscribe();
      return;
    }
    if (this.itemSize !== this.currentItem) {
      this.el.nativeElement.scrollTop = height + 2;
    } else {
      this.el.nativeElement.scrollTop = 0;
    }
  }
}
